import 'dart:math';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/custompage/msg_group_manager.dart';
import 'package:find_friend/pages/im/model/groupmodel.dart';
import 'package:find_friend/pages/im/pages/conversation_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


class MsgGroupFriendPage extends StatefulWidget {

  @override
  _MsgGroupFriendPageState createState() => _MsgGroupFriendPageState();
}

class _MsgGroupFriendPageState extends State<MsgGroupFriendPage> {

  List<GroupModel> list = [];

  @override
  void initState() {
    super.initState();
    
    EventMineBus.instance.addListener(EventMineKeys.IMGroupRefresh, (arg) {
      _requestData();
    });
    _requestData();
  }

  @override
  void dispose() {
    EventMineBus.instance.removeListener(EventMineKeys.IMGroupRefresh);
    super.dispose();
  }

  _requestData() {
    Networktool.request(API.friend, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        IMGroupResponse response = IMGroupResponse.fromJson(data);
        if(response.data != null) {
          list = response.data;
          if(mounted) setState(() {});
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index){
          return MessageGroupAnimationCell(model: list[index]);
        }
      );
  }
}

class MessageGroupAnimationCell extends StatelessWidget {
  
  final GroupModel model;
  final Function() onModRemarkName;

  const MessageGroupAnimationCell({Key key, this.model, this.onModRemarkName}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MsgGroupCell(
      groupcount: model.friend.length,
      groupname: model.friendgroup,
      itemHeight: 60.h,
      children: List.generate(model.friend?.length ?? 0, (index) => MsgGroupUserCell(model: model.friend[index])),
    );
  }
}

class MsgGroupUserCell extends StatefulWidget {
  const MsgGroupUserCell({
    Key key,
    @required this.model,
  }) : super(key: key);

  final FriendModel model;

  @override
  _MsgGroupUserCellState createState() => _MsgGroupUserCellState();
}

class _MsgGroupUserCellState extends State<MsgGroupUserCell> {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Map arg = {"targetId":widget.model.mobile, "nickname":widget.model.followRemark,};
        push(context, ConversationPage(
          arguments: arg,
          onModRemarkName: (name) {
            widget.model.followRemark = name;
            setState(() {
              
            });
          },
        ));
      },
      child: Container(
          color: Colors.white,
          height: 60.h,
          padding: const EdgeInsets.only(bottom: 10, right: 26, left: 26,),
          child: Row(
            children: [
              CustomCircleAvatar(size: 46.h, url: widget.model.avatar,),
              SizedBox(width: 7,),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(widget.model.remarkname ?? "", style: instanceTextStyle(14, APP_font_black),),
                  SizedBox(height: 5,),
                  Text("${widget.model.bio ?? ''}", style: instanceTextStyle(10, APP_font_black),)
                ],
              )
            ],
          ),
        ),
    );
  }
}



class MsgGroupLeadingWidget extends StatelessWidget {

  final double val;
  final String groupname; // 分组名称
  final int groupcount;   // 组员数

  const MsgGroupLeadingWidget({Key key, this.val, this.groupname, this.groupcount}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 11.5.h),
        child: Row(
          children: [
            Transform.rotate(
              angle: -pi / 2 * val,
              child: Image.asset("assets/tan.png", width: 11, height: 11,)
            ),
            SizedBox(width: 7.5),
            Expanded(child: Text(this.groupname, style: instanceTextStyle(15, APP_font_black),)),
            Text("$groupcount人",style: instanceTextStyle(10, const Color(0xff999999)),)
          ],
        ),
      );
  }
}

class MsgGroupCell extends StatefulWidget {

  final List<Widget> children;
  final double itemHeight;
  final Function(bool) onTap;
  final String groupname;
  final int groupcount;

  const MsgGroupCell({Key key, this.children, this.itemHeight, this.onTap, this.groupname, this.groupcount}) : super(key: key);

  @override
  _MsgGroupCellState createState() => _MsgGroupCellState();
}

class _MsgGroupCellState extends State<MsgGroupCell> with SingleTickerProviderStateMixin {

  Animation<double> _animation;
  AnimationController _controller;
  List<Widget> children;
  double allheight;
  bool isselect = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    CurvedAnimation _curve = CurvedAnimation(curve: Curves.easeInOutCirc, parent: _controller);
    _animation = Tween<double>(end: 1.0, begin: 0.0).animate(_curve);


    _controller.addListener(() {  // 需要加上这一段，不然没有作用
      setState(() {
        
      });
    });

    setState(() {
      children = widget.children ?? [];
      allheight = children.length * widget.itemHeight;
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    
    final size = MediaQuery.of(context).size;

    return Column(
          children: [
            GestureDetector(
              onTap: (){
                setState(() {
                  isselect = !isselect;
                });
                if(widget.onTap != null)widget.onTap(true);
                if(_controller.status == AnimationStatus.completed) {
                  _controller.reverse();
                  if(widget.onTap != null)widget.onTap(false);
                } else {
                  _controller.forward();
                }
              },
              onLongPress: (){
                // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => MsgGroupManagerPage()));
                push(context, MsgGroupManagerPage());
              },
              child: MsgGroupLeadingWidget(val: 1 - _animation.value, groupname: widget.groupname, groupcount: widget.groupcount,)
            ),
            Offstage(
              offstage: !isselect,
              child: Container(
                height: _animation.value * allheight,
                width: size.width,
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                ),
                child: SingleChildScrollView(
                  physics: NeverScrollableScrollPhysics(),
                  child: Column(
                    children: children ?? [],
                  ),
                ),
              ),
            )
          ],
        );
  }
}